home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11154 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  87 lines

  1. Newsgroups: comp.lang.c
  2. Path: alisa.org!wjjr
  3. From: wjjr@alisa.org (John J. Rushford)
  4. Subject: Re: Unix Pipes and descrpitors
  5. X-Newsreader: TIN [version 1.2 PL2]
  6. Organization: My place on the Front Range.
  7. Message-ID: <DonJst.HHq@alisa.org>
  8. References: <Pine.ULT.3.91.960319174425.8464A-100000@midir>
  9. Date: Fri, 22 Mar 1996 04:43:41 GMT
  10.  
  11. Colm Connolly (colmconn@midir.ucd.ie) wrote:
  12. : Having created a pipe, how do I access the file descriptors created by the 
  13. : pipe system call after I call exec? I'd be grateful if someone could help 
  14. : me with this. 
  15.  
  16. : Colm Connolly.
  17.  
  18. : PS Manuals or books for that matter haven't helped much with this!! 
  19.  
  20. A pipe is half duplex which means you can read from it or write to it.  Keeping
  21. this in mind, you may want to create two pipes if you need to read from and
  22. write to the forked child where you do the exec().
  23.  
  24. Anyway, say you are going to read stdout of the child from the parent and you
  25. want to write to stdin of the child from the parent then:
  26.  
  27.     int fda[2], fdb[2], pid, status;
  28.  
  29.     /*
  30.      * full duplex pipeline.
  31.      */
  32.     if (pipe (fda) < 0 || pipe (fdb) < 0) {
  33.     exit (1);
  34.     }
  35.  
  36.     if ((pid = fork ()) < 0) {
  37.     exit (2);
  38.     }
  39.  
  40.     if (pid == 0) {  /* in the child */
  41.  
  42.     /* set up read half of pipeline on stdin */
  43.     close (0);
  44.     dup (fda[0]);
  45.     close (fda[0]);
  46.     close (fda[1]);
  47.  
  48.     /* set up write half of pipeline on stdout */
  49.     close (1);
  50.     dup (fdb[1]);
  51.     close (fdb[1]);
  52.     close (fdb[0]);
  53.  
  54.     /*
  55.      * the pipe file descriptors are now stdin and stdout of the
  56.      * child process so, exec () your program.
  57.      */
  58.  
  59.      exec();
  60.     }
  61.  
  62.     if (pid > 0) { /* in the parent */
  63.  
  64.     /* set up parents half of the pipeline. */
  65.     close (fda[0]);
  66.     close (fdb[1]);
  67.  
  68.     /*
  69.      * fda[1] is used to write to stdin of the child.
  70.      * fdb[0] is used to read from stdout of the child.
  71.      * use fdopen() on the above two file descriptors if
  72.      * you want to use stdio on these descriptors otherwise.
  73.      * use read() or write().
  74.      */
  75.  
  76.     wait (&status);
  77.     }
  78.  
  79. Of couse this was implemented on a Unix system.  Hope this is usefule.
  80.  
  81. regards
  82. -- 
  83. John J. Rushford              
  84. Westminster, Colorado___/\_/\_
  85. wjjr@alisa.org (alisa.org is powered by FreeBSD)
  86.  
  87.